import java.util.Arrays;

/**
 * Created by zhourh on 2018/9/6.
 *
 * 给定两个字符串 s 和 t ，编写一个函数来判断 t 是否是 s 的一个字母异位词。

 示例 1:

 输入: s = "anagram", t = "nagaram"
 输出: true
 示例 2:

 输入: s = "rat", t = "car"
 输出: false

 */
public class ValidAnagram {

    public static void main(String[] args) {
        System.out.println(new ValidAnagram().isAnagram2("anagram", "nagaram"));
        System.out.println(new ValidAnagram().isAnagram2("rat", "car"));
    }

    public boolean isAnagram(String s, String t) {
        if (s == null || t == null || s.length() != t.length()) {
            return false;
        }


        char[] sChars = s.toCharArray();
        char[] tChars = t.toCharArray();

        Arrays.sort(sChars);
        Arrays.sort(tChars);

        return new String(sChars).equals(new String(tChars));

    }

    public boolean isAnagram2(String s, String t) {
        if (s == null || t == null || s.length() != t.length()) {
            return false;
        }


        char[] sChars = s.toCharArray();
        char[] tChars = t.toCharArray();

        int[] sCounts = new int[26];
        int[] tCounts = new int[26];

        for (int i = 0; i < sChars.length; i++) {
            sCounts[sChars[i] - 97]++;
            tCounts[tChars[i] - 97]++;
        }

        for (int i = 0; i < 26; i++) {
            if (sCounts[i] != tCounts[i]) {
                return false;
            }
        }

        return true;

    }
}
